//
//  dataController.swift
//  coredata使用
//
//  Created by xuNick on 16/11/9.
//  Copyright © 2016年 NN. All rights reserved.
//

import UIKit
import CoreData
class CoredataManager: NSObject {
    
    static let managedObjectContext: NSManagedObjectContext = {
        let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
        let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
        queue.async {
            let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
            let docURL = urls[urls.endIndex-1]
            /* The directory the application uses to store the Core Data store file.
             This code uses a file named "DataModel.sqlite" in the application's documents directory.
             */
            //            let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
            let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
            do {
                try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
            } catch {
                fatalError("Error migrating store: \(error)")
            }
        }
        return managedObjectContext
    }()
    static var managedObjectModel: NSManagedObjectModel = {
        // This resource is the same name as your xcdatamodeld contained in your project.
        guard let modelURL = Bundle.main.url(forResource: "coredataTest", withExtension:"momd") else {
            fatalError("Error loading model from bundle")
        }
        // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
        guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }
        return mom
    }()
    static var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
        return persistentStoreCoordinator
    }()
    
    
//    //保存上下文
//    static func save(){
//        let context = CoredataManager.shareManager.managedObjectContext
//        do {
//            try context.save()
//        }catch{
//            fatalError("Failure to save context: \(error)")
//        }
//    }
//    
//    //增加数据
//    static func insertObject(){
//        
//    }
//    //增加多条数据
//    static func appendObjects(){
//        
//    }
//    
//    //删除数据
//    static func deleteObject(){
//        
//    }
//    
//    //更新数据
//    static func updateObject(){
//        
//    }
}
